#include "c1.h"
#include "ui_c1.h"

#include "c2.h"

c1::c1(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::c1)
{
    ui->setupUi(this);

    this->setWindowTitle("8888端口");
    this->move(200, 200);

    c2 *c = new c2;
    c->show();
    c->move(1000, 200);

    this->socket1 = new QUdpSocket(this);
    this->socket1->bind(8888);

    connect(ui->sendBtn, &QPushButton::clicked, [this](){
        QByteArray msg = ui->sendLine->text().toUtf8();
        QString ip = ui->ipLine->text();
        int port = ui->portLine->text().toInt();
        this->socket1->writeDatagram(msg, QHostAddress(ip), port);

        ui->sendLine->clear();
    });

    // 每当有数据发送过来时了，都会触发 readyRead 信号
    connect(socket1, &QUdpSocket::readyRead, [this](){
        char buf[1024] = { 0 };
        QHostAddress ip;
        quint16 port;
        this->socket1->readDatagram(buf, 1024, &ip, &port);
        QString msg = QString("%1:%2  --> %3").arg(ip.toString()).arg(port).arg(buf);
        ui->textEdit->append(msg);
    });
}

c1::~c1()
{
    delete ui;
}
